<script>
import Schema from 'async-validator';
import * as api from "./api";
import { request } from "@xiaoe/js-tools/lib/request";
import loading from "@xiaoe/goose/lib/loading";
import { isIos,isBrandApp, isELearnApp, isEcommunityApp, isQlive, isVideoDistribution, isKSMiniProgram, isAliveIframe, isMiniEnv, getClientEnv } from "../../utils/checkEnv"
import { postCouponList } from "./postCouponList.js";
import {sensorsTrackButton, sensorsViewPage} from "../../utils/sensors_report";
import { isEmptyObject, debounce, getDataIfWxChannel, getFileTiming, setOrderCache } from "../../utils/index";
import { resolveChannelInfo } from "../../utils/channel-info";
import { getMiniProType } from "../../utils/mini-pro-type"
import { getspecialByType } from '../special-pay';
import { PayBackHandler } from '../../strategy/pay-back-handler'
import CopyPasswordDialog from '../CopyPassword/index.js'
import { getJumpUrls } from './jump-url'
import { Parameter, GoodsList, GoodsOrderList, MiscParameter, valuate, createOrderInLive, getPaymentByType, producePayParams, CouponInfo, PromoCodeInfo, ActivityInfo, IdentityInfo, PointInfo, DeliveryInfo, LevelMemberInfo, CartGoodsList, PAY_WAY, PAY_WAY_LIST } from "@xiaoe/etransaction";
import { KEY_STORAGE_SITE, ORDER_PAY_STATUS, MARKETING_SEC_KILL, KEY_STORAGE_DELIVERY_MODE, DELIVERY_MODE, PAY_TAB_LIST, MARKETING_FISSION_POSTER, SUB_ORDERS, PAY_TYPE_LIST, IdentityType, CREATE_ORDER_CODE, SHIELD_ACTIVITY, IFRAME_SPECIAL_PAY, DELIVERY_METHOD_TEXT } from '../../constants/index';
import {
  ENTITY_GOODS,
  COP_GOODS,
  ASSOCIATION,
  OFFLINE_CLASS,
  OFFLINE_PERIOD
} from "../../constants/constant.js";
import ModeSelect from "../ModeSelect";
import Address from "../Address";
import locale from "../../../../mixins/locale";
import LeaveWord from "../LeaveWord";
import PayDetail from "../PayDetail";
import CouponShow from '../CouponShow'
import GoodsInfo from '../GoodsInfo'
import IntegralSelect from '../IntegralSelect'
import SvipSelect from '../SvipSelect'
import InvoiceShow from '../InvoiceShow'
import PickupSelect from '../PickupSelect'
import InfoCollectionWrapper from '../InfoCollectionWrapper'
import MemberLevel from "../MemberLevel"


import OrderBar from "../OrderBar";
import PayWay from "../payWay";
import {getPickerInfo, getPickerList, fetchPayWay, fetchCollectInfo} from "../../fetch-data";
import { AddressRule, PickInfoRule, InfoCollectionRule, OfflineClassRule, ActivityApplyRule } from "../validator";
import EventBus from '../../utils/eventbus'
import GuideLoading from "../GuideLoading/index.vue";

import { Skynet, LogLevel, LogType } from "@xiaoe/skynet";

import {Toast} from "vant";
import {SVIP} from "../../utils/constants";

//config可选
export const skynet = new Skynet({
  projectName: "live-pay",
  projectVersion: "v1.0.0",
  auto: false,
  url: "https://logreport.xiaoeknow.com/ecommerce/report",
});

skynet.turnOn();

const MINMUM_PRICE_TYPE_MAP = {
  NORMAL: 1,
  SVIP: 2,
  MARKETING: 3
}
const DEFAULT_PAY_WAY = [{ name: '微信支付', pay_way: 6 }];

export default {
  name: "confirmOrder",
  props: {
    confirmDetail: Object,//订单页数据
    aliveInfo: {
      type: Object,
      default: ()=>{},
    },
    boxshow: {
      type: Boolean,
      default: false,
    },
    baseInfoQuery: {
      type: Object,
      default: () => {},
    },
    isCart: {
      type: Number,
      default: 0,
    },
    isTeam: {
      type: Boolean,
      default: false,
    },
    cartGoodsList: {
      type: Array,
      default: () => [],
    },
    popupRoundStyle: {
      type: Object,
      default: () => {
        return {
          height: "80%",
        };
      },
    },
    goodsMsg: { // 从商品卡片进入的标识
      type: Boolean,
      default: false,
    },
    useScatter:{
      type: Boolean,
      default: false
    },
  },
  components: {
    loading,
    ModeSelect,
    Address,
    LeaveWord,
    GoodsInfo,
    CouponShow,
    IntegralSelect,
    SvipSelect,
    // OfflineClass,
    PayDetail,
    InvoiceShow,
    PickupSelect,
    InfoCollectionWrapper,
    OrderBar,
    PayWay,
    GuideLoading,
    MemberLevel
  },
  mixins: [locale],
  data(){
    return{
      baseInfo: this.baseInfoQuery,
      createOrderloading: false, // loading溜达鹅显示隐藏
      showLoadingE: false, // loading溜达鹅显示隐藏
      isFullScreen: false, //是否全屏显示溜达鹅
      loadingText: '', // loading文案
      showPopup: false, // 是否弹出确认订单弹框
      superVipInfo: {}, // svipInfo 超级会员信息
      userIsVip: false, // 用户是否是超级会员
      marketingData: {}, //营销数据
      marketingDataLoaded: false, //营销数据加载
      isLoadedEnd:false, //余额接口是否加载完毕
      valuateParams: new Parameter(),//批价参数
      payParams: new Parameter(),//支付参数
      valuateData: {},//批价返回参数
      prePayInfo: {}, //批价信息
      allData: [], // 积分规则明细
      virtualInfo:{}, //余额信息
      supportVirtual:false, //是否支持虚拟币支付
      cu_id:'', //埋点上报cu_id
      addressInfo: {}, // 地址信息（非自提）
      huabeiParams: {},
      confirmOrderInfo: {
        // 订单页详细信息(通过查询接口拿到)
        app_info: {},
        goods_info: {},
      },
      distributionMode: 0, //配送方式 -1全部 1快递配送 2商品自提 （目前只支持实物商品，非实物商品返回0）
      userCanPick: 1, //商家是否支持自提 1支持 0不支持
      resource_id: "",
      shopConf: {},
      isEnterpriseLive: getClientEnv("qlive_shop"), // 是否为企业直播端
      processing: "",
      activeMode: 1, // 1：快递配送，2：自提
      pickerUserInfo: {}, // 自提人信息
      shipperType: 1, // 1：新建自提人；2：编辑自提人
      updateShipperInfo: {}, // 需要修改的自提人信息
      businessConf: {}, //featureInfo 商品特征
      waitInformation: true, // 是否是第一次批价，用来第一次批价等信息采集接口返回
      formData: {
        address: null,  // 收货地址
        pickInfo: {
          site: null,
          picker: null
        }, // 自提信息，包括自提人、自提点
        infoCollectionInfo: null,//信息采集参数
        eduInfo: {
          course_id: ''
        },  // 线下课学员信息
        goodsInfo: {},  // 商品信息
        invoiceInfo: {
          invoice_type: 0
        }, // 发票信息
        userRemark: '', // 留言
        isUseIntegral: false, // 是否使用积分
        isInitPoint:true, //积分抵扣标识
        couponInfo: {
          isSelected: false,
          selectedCoupons: []
        }, // 优惠券信息
        promoCodeInfo: '',  // 优惠码信息
        teamBuy: {},  // 拼团
        activityApplyInfo: [], // 活动管理报名信息
        beforePay: {}, // 支付前校验函数
        checkList: {}, // 支付前校验信息
        count: this.baseInfoQuery.count || 1,
        identityType: IdentityType.ANSWER, // 身份特权类型: -1 不参加任何优惠, 0 都需要查询, 1 超级会员
      },//表单数据，如自提信息、优惠券、信息采集 等等
      pickerList: [],	// 自提人列表
      isPromoterPicksUp: false, // 推广员默认地址不支持选择修改地址
      pickSiteInfo: {},  // 选择的自提点信息
      isCoursePeriodGray: false, // 是否是有效期灰度店铺
      isCreateOrderDisabled: false,//禁止提交订单
      payWayList:[],
      payWay:0,
      setTime: null,// 计时器
      infoIsLoadSuc: true,//信息采集加载状态
      needCollect: true, //信息采集状态二次确认
      infoCollectionLoaded: [],//信息采集加载完成的时间
      huaBeiInstallment: [],//信息采集加载完成的时间
      orderBarShow:true, //确认订单栏是否显示
      assertNeedCollectInfo:{},
      jumpData: {
        paySuccessUrl: '',
        payFailUrl: ''
      },
      isShowGuideLoding: false, // 是否显示引导刷新加载
      createTimer: null,
      sku_floor_price: null,  // 商品低价
      sku_floor_type: 0, //0 不设置 1 底价 2 优惠券最大抵扣金额
      currencyInfo:{},//外币汇率信息
      memberLevelInfo:{}, //会员等级相关数据
      customDeliveryType: [DELIVERY_METHOD_TEXT.EXPRESSAGE, DELIVERY_METHOD_TEXT.PICK],//自定义配送方式顺序-由b端交易设置修改
      packageInfo: null, //赠品信息
      isRetryPayWay: 0,
      showPicker: true, // 0必填，1可选，2隐藏
      isHideSelfPickerInfo: 0 //自提人是否必填 0——必填，1——可选，2——隐藏，不需要填
    }
  },
  computed: {
    //是否展示会员等级模块
    showMemberLevel(){
      return this.memberLevelInfo?.is_show_level_member
    },
    // 是否是购物车过来的
    isCartTemp() {
      return this.baseInfo.isCart;
    },
    marketingLowPrice() {
      if ([3, 6].includes(this.marketInfo?.activity_type)) {
        return this.marketInfo?.low_price;
      }
      if ([8].includes(this.marketInfo?.activity_type)) {
        const { is_subscribe, user_s0ubscribed, in_activity } = this.marketInfo;
        if (is_subscribe === 1 && user_subscribed === 0 && in_activity === 1) {
          return null;
        }
        // 如何没库存则按原价来计算券后价
        if (this.marketInfo?.event_has_stock === 0) {
          return null;
        }
        return this.marketInfo?.low_price;
      }
      return null;
    },
    marketInfo() {
      return this.marketingData?.marketing_info || {};
    },
    isSvipUseful() {
      return (
        this.superVipInfo?.svip_purchase_valid === 1 &&
        this.superVipInfo?.svip_info?.svip_state === 0 &&
        this.superVipInfo?.svip_info?.single_resource_rights?.rights_type === 2 && // 增加超会折扣权益判断
        this.userIsVip
      )
    },
    hasEntityGoods() {
      return this.packageInfo?.entity_goods_num > 0 || this.goodsInfo?.spu_type === ENTITY_GOODS;
    },
    //显示地址: 非积分+快递配送+有实物商品
    showAddress() {
      // return this.showAddressSelect && (
      //   this.baseInfo.spu_type === ENTITY_GOODS ||
      //   (this.goodsInfo.is_goods_package && this.hasEntityGoods)
      //   || this.baseInfo.spu_type === COP_GOODS
      // )
      if (this.activeMode !== DELIVERY_MODE.EXPRESSAGE) return false;
      if ((this.distributionMode === -1 || this.distributionMode === 1) && this.goodsInfo.spu_type === COP_GOODS) return true // 组合商品
      return this.hasEntityGoods;
    },
    invalidAddress() {
      if (this.activeMode === 1) {
        return this.addressInfo?.calculate_freight === false;
      }
      return false;
    },
    ratePrice() {
      return this.valuateData?.rate_price || '--.--'
    },
    //显示信息采集
    showInfoCollection() {
      const { isCart, isSendFriend } = this.baseInfo;
      if (isCart) return false;//购物车不支持
      if (isVideoDistribution) return false;//视频号分销小程序不支持
      if (isKSMiniProgram) return false;//快手小程序不支持
      if (isBrandApp) return false;//品牌app不支持
      if (isSendFriend) return false; // 送好友不支持
      if (isEcommunityApp) return false; // 鹅圈子APP
      return true;
    },
    showOfflineClass() {
      return [OFFLINE_CLASS, OFFLINE_PERIOD].includes(this.goodsInfo?.spu_type);
    },
    // 商品信息
    goodsInfo() {
      if (isEmptyObject(this.confirmOrderInfo.goods_info)) {
        return this.baseInfo;
      }
      // 老接口 兼容新组建结构处理
      if (this.confirmOrderInfo.goods_info.sku_info){
        this.confirmOrderInfo.goods_info.sku_info.sku_id = this.confirmOrderInfo.goods_info.sku_id;
        this.confirmOrderInfo.goods_info.sku_info.sku_min_purchase = this.confirmOrderInfo.goods_info.sku_min_purchase;
      }else{
        this.confirmOrderInfo.goods_info.sku_info = {
          sku_id:this.confirmOrderInfo.goods_info.sku_id,
          sku_min_purchase:this.confirmOrderInfo.goods_info.sku_min_purchase,
        }
      }
      this.confirmOrderInfo.goods_info.sku_info.expire_info = {
        expire_desc: this.confirmOrderInfo.goods_info.sku_info.expire_desc,
        is_expire_display: this.confirmOrderInfo.goods_info.sku_info.is_expire_display,
      }

      let attr_value = this.confirmOrderInfo.goods_info.attr_value
          .map((spec) => {
            return spec.attr_value;
          })
          .join(";")
      this.confirmOrderInfo.goods_info.attr_value = {
        attr_value
      }

      return this.confirmOrderInfo.goods_info;
    },
    // 显示配送方式
    showMode() {
      return this.distributionMode === -1 && this.userCanPick === 1;
    },
    // 显示自提
    showPickSelect() {
      return this.activeMode === DELIVERY_MODE.PICK;
    },
    //显示优惠券
    showCoupon() {
      const { isIntegral, renew } = this.baseInfo;
      if (isIntegral) return false;
      //续费
      if (renew == 1) return false;
      //大客户特殊逻辑，没有优惠券时隐藏整个优惠券栏
      return !this.valuateData?.hide_coupon;
    },
    // 是否展示积分
    showIntegral() {
      return !(isQlive || this.isIntegral || !this.valuateData?.points_info?.is_show_point);
    },
    // 是否是积分兑换
    isIntegral() {
      if (this.confirmOrderInfo?.goods_info?.sell_mode === 9) {
        this.baseInfo.isIntegral = true
      }
      return this.baseInfo.isIntegral;
    },
    showSvip() {
      return this.valuateData?.identity_info?.is_show_svip;
    },
    svipDiscount() {
      return this.valuateData?.identity_info || {};
    },
    // 圈子app 走这里不与其他app耦合
    showRechargeCircle(){
      return isEcommunityApp
    },
    showRecharge(){
      return (isBrandApp || isELearnApp)
    },
    zeroPay() {
      return this.valuateData?.price_info?.final_price === 0
    },
    showPayDetail() {
      return !isQlive && this.valuateData?.price_info;
    },
    showInvoice() {
      return !this.isIntegral && this.shopConf.enable_invoice === 1;
    },
  },
  async created() {
    EventBus.$on("order_onInfoCollectionLoaded",({needCollect, isLoad})=>{
      this.infoIsLoadSuc = isLoad
      this.needCollect = needCollect
      this.waitInformation = false // 信息采集接口返回成功，不需要等
      if(this.setTime){ // 等待中的话
        clearTimeout(this.setTime) //不等待了
        this.loadingStatus(false);
        this.setTime = null
      }
      const time = `第${this.infoCollectionLoaded.length + 1}_${new Date().getTime()}_${needCollect}`
      this.infoCollectionLoaded.push(time)
      this.infoCollectionReport(isLoad)
    })
    if (this.baseInfoQuery.isAlive === 1) {
      api.changealivePrefix("/_alive");
      this.processing = "/_alive";
    } else {
      api.changealivePrefix("");
      this.processing = "";
    }
  },
  async mounted() {
    const orderInfo = await this.initConfirmOrderInfo().catch(err=>{
      console.error(err);
      skynet.report({
        details: {
          keyword: "confirmOrder_init_confirm_order_info_error",
        },
        err,
        level: LogLevel.ERROR,
        type: LogType.HTTP_ERROR,
      });
      return null;
    });
    //有营销活动、超级会员再请求对应接口，降低接口流量
    const {has_activity, has_svip} = orderInfo?.data?.marketing || {}

    const tasks = []

    //超级会员获取超级会员相关信息放在前面是因为领券需要判断
    if(has_svip) {
      tasks.push(this.initSuperVipInfo());
    }
    // 营销活动相关信息放在前面是因为领券需要判断
    if (!this.isCart && has_activity) {
      tasks.push(this.initMarketingData())
    }

    if(tasks.length) {
      await Promise.all(tasks)
    }

    //非购物车进入 品牌app 鹅学习app
    if(isBrandApp || isELearnApp){
      this.initBeatApp()
      this.getCanUseVirtual()
    }
    if (this.boxshow && this.baseInfoQuery) {
      await this.initData(orderInfo);
    }
  },
  methods:{
    // 自动领取优惠券
    async autoReceiveCoupon() {
      if (this.goodsMsg || this.baseInfoQuery.hasPreferentialPrice) {
        const {resource_id, resource_type, spu_id, superVipPrice, price} = this.baseInfoQuery;

        // 营销最低价
        const marketingLowPrice = this.marketInfo?.in_activity && this.marketingLowPrice;
        // 超会和营销活动是否能叠加
        const isSvipSupportMarketing = this.marketInfo?.is_super_vip === 1;

        const svipDiscount = this.superVipInfo?.svip_info?.svip_info?.discount / 10

        let isSvipCanUseCoupon = (this.superVipInfo.svip_info?.svip_info?.is_coupons === 1)
        // // 原价
        let minimumPrice = price;
        let minimumPriceType = MINMUM_PRICE_TYPE_MAP.NORMAL

        // 超级会员营销叠加价格
        const marketingSvipPrice = this.isSvipUseful && isSvipSupportMarketing && marketingLowPrice * svipDiscount;

        // 有超级会员价
        if (superVipPrice) {
          if (
            // 没有营销价或者营销价低于超级会员价
            (!marketingLowPrice || marketingLowPrice && superVipPrice < marketingLowPrice) &&
            this.userIsVip // 用户是超级会员
          ) {
            // 以超级会员价计算券后价
            minimumPrice = superVipPrice;
            minimumPriceType = MINMUM_PRICE_TYPE_MAP.SVIP;
          }
        }

        // 当前仍是原价的情况下，有营销价，使用营销价计算券后价
        if (minimumPriceType === MINMUM_PRICE_TYPE_MAP.NORMAL) {
          if (marketingLowPrice) {
            minimumPrice = marketingSvipPrice || marketingLowPrice;
            minimumPriceType = MINMUM_PRICE_TYPE_MAP.MARKETING;
          }
        }

        // 当前以超级会员逻辑计算券后价，但没开启超级会员叠加使用优惠券，不获取券后价
        if (minimumPriceType === MINMUM_PRICE_TYPE_MAP.SVIP && !isSvipCanUseCoupon) {
          // 当前以超级会员逻辑计算券后价，但没开启超级会员叠加使用优惠券，不进行自动领券
          // if (this.boxshow && this.baseInfoQuery) {
          // await this.initData();
          // }
          return;
        }
        let params = {
          resource_type,
          resource_id: resource_id || spu_id,
          minimum_price: minimumPrice,
          minimum_price_type: minimumPriceType,
          svip_coupon_over: this.isSvipUseful && isSvipCanUseCoupon,
          spu_id: spu_id
        }
        if (this.sku_floor_price){
          params.floor_price = this.sku_floor_price
          params.floor_type = this.confirmOrderInfo.goods_info.sku_info?.sku_floor_type
        }
        await postCouponList(params).then((res) => {
          // console.log('postCouponList==>',res);
          this.$toast(this.t('confirmOrder_bestDiscount_placeOrder'));
          // if(res && res.needDoValuate){
          //   //领取了优惠券，需要重新批价
          //   this.loadingStatus(false);
          //   this.doValuate(13)
          // }
        }).catch((err) => {
          console.log("优惠券获取列表报错或者没有可领券", err)
        })
      }
    },
    // 点击刷新按钮
    onRefresh() {
      console.log('刷新');
      this.initData();
    },
    //刷新次数达到上限
    onRefreshExceed() {
      this.$emit("refresh-exceed");
    },
    onCountChange(count,isInit) {
      if (this.formData.count !== count) {
        this.formData.count = count;
        this.baseInfo.count = count;
        if (!this.isCart && !isInit) {
          this.doValuate(1);
        }
      }
    },
    loadingStatus(val) {
      this.showLoadingE = val;
    },
    // 获取超级会员相关信息
    initSuperVipInfo() {
      this.loadingStatus(true);

      let params = {
        resource_id: this.baseInfo.resource_id || this.resource_id,
        resource_type: this.baseInfo.resource_type,
      };
      return api.getSuperVipInfo(params).then((res) => {
        if (res.code === 0) {
          this.superVipInfo = res.data;
          this.userIsVip = (this.superVipInfo?.svip_info?.user_svip_info?.state === 1)
          // // 判断是否需要更新超级会员相关数据
          // let shouldUpdate = superVipMarketingCompare(state, res.data);
          // let spuType = state.goods_detail.baseInfo.spu_type;
          // let isMatchType = SVIP_SPU_TYPE.includes(spuType);
          // if (shouldUpdate && isMatchType) {
          //   commit('goods_detail/footer_button/setSuperVipBackground', true);
          //   commit('goods_detail/sku_selector/setSuperVipSku', res.data);
          // }
        }else{
          skynet.report({details:{
              keyword:'confirmOrderPage_init_svip_info_code_error',
              message:"当页支付确认订单异常-获取超级会员相关信息",
              reportData: res
            },level: LogLevel.ERROR,type: 'CurrentPay'})
        }
      }).catch(err=>{
        skynet.report({details:{
            keyword:'confirmOrderPage_init_svip_info_catch_error',
            message:"当页支付确认订单异常-获取超级会员相关信息",
            reportData: err
          },level: LogLevel.FATAL,type: 'CurrentPay'})
      }).finally(()=>{
        this.loadingStatus(false);
      });
    },
    initMarketingData() {
      let params = {
        spu_id: this.baseInfo.id,
        spu_type: this.baseInfo.spu_type,
        resource_type: this.baseInfo.resource_type,
      };
      return api.getMarketingInfo(params).then((res) => {
        if (res.code === 0) {
          let marketing_info = res.data.marketing_info;
          if (
            marketing_info?.activity_type === 3 &&
            !(
              (marketing_info?.all_stock > 0 &&
                marketing_info?.now_stock > 0) ||
              marketing_info?.all_stock == 0
            ) &&
            ![21, 29, 41, 42].includes(marketing_info.resource_type)
          ) {
            // 这里的逻辑要注意，如果接口返回了营销信息但工程拿不到的话，问题就在这里。
            // 如果是限时折扣，且达到了限量后，就应该不显示限时折扣的信息了，我选择在源头就断了这个数据，但保留了推广员的信息
            // 且这里不能是多规格的商品，因为多规格的商品没有限量的设置，如果你看到的时候已经准备有了，麻烦跟产品说这需求咱不接，咱不受这鸟气
            res.data.marketing_info = null;
          }
          skynet.report({details:{message:"当页支付确认订单正常获得原始营销数据", reportData: res},level: 'INFO',type: 'CurrentPay'})
          this.marketingData = res.data;
        } else {
          skynet.report({details:{
              keyword:'confirmOrderPage_init_marketing_info_code_error',
              message:"当页支付确认订单异常获得原始营销数据",
              reportData: res
            },
            level: LogLevel.ERROR,
            type: 'CurrentPay'})
          this.marketingDataLoaded = true;
        }
      }).catch(err => {
        skynet.report({details:{
            keyword:'confirmOrderPage_init_marketing_info_catch_error',
            message:"当页支付确认订单异常获得原始营销数据",
            reportData: err
          },
          level: LogLevel.FATAL,
          type: 'CurrentPay'})
      });
    },
    // 初始化数据，请求相应接口
    async initData(orderInfo) {
      if (!this.shopConf || isEmptyObject(this.shopConf)) {
        // 页面刷新重新初始化店铺设置信息
        this.initShopConf();
      }
      this.initDeliveryState();
      try {
        if(!orderInfo) {
          orderInfo = await this.initConfirmOrderInfo();
        }

        if (orderInfo.code === 0 && this.baseInfo.spu_type == "ENT" && orderInfo.data?.goods_info?.distribution_pattern === -1 && this.userCanPick === 1) {
          this.customDeliveryType = orderInfo.data?.distribution_pattern_config;
          this.activeMode = this.customDeliveryType[0] === DELIVERY_METHOD_TEXT.EXPRESSAGE ? DELIVERY_MODE.EXPRESSAGE : DELIVERY_MODE.PICK;
        }

        this.handleOrderInfo(orderInfo);
        const packageInfo = orderInfo.data.is_package_info;
        if (packageInfo?.has_package) {
          this.handleGoodsPackageInfo(packageInfo);
        }
        this.loadingStatus(false);
        fetchCollectInfo(this.baseInfo.resource_type,this.baseInfo.resource_id || this.resource_id,'buy_page').then(res=>{
          this.assertNeedCollectInfo = res
        }).catch(err => {
          skynet.report({details:{
              keyword:'confirmOrderPage_init_fetch_collect_info_error',
              message:"当页支付确认订单异常-处理初始化订单页基本信息",
              reportData: err
            },level: LogLevel.FATAL,type: 'CurrentPay'})
        })
      } catch (err){
        skynet.report({details:{
            keyword:'confirmOrderPage_init_confirm_order_catch_error',
            message:"当页支付确认订单异常-处理初始化订单页基本信息",
            reportData: err
          },level: LogLevel.FATAL,type: 'CurrentPay'})
      } finally {
        this.$emit('dataLoaded')
      }
      this.initBusinessFeatureConfIfNeed();
      this.initFormData()
      await this.doValuate(2)
    },
    // 初始化支付方式
    initPayway(token){
      this.loadingStatus(true);
      const { shareType: share_type, contentAppId: content_app_id, shareUserId: share_user_id } = this.baseInfo;
      const default_pay_way = window.appId === 'appraeurmxf5923' ? [{ name: '微信支付', pay_way: 17 }] : DEFAULT_PAY_WAY;

      const params = {
        goods_list: [{
          content_app_id: content_app_id || this.goodsInfo?.parent_app_id,
          spu_id: this.isCart ? this.cartGoodsList?.[0]?.spu_id: this.goodsInfo?.spu_id,
          sku_id: this.isCart ? this.cartGoodsList?.[0]?.sku_id: this.goodsInfo?.sku_id,
        }],
        app_id: window.APPID,
        user_id: window.USERID,
        is_team_buy: false,
        share_type,
        share_user_id,
        token, // 花呗批价token
        team_buy_id: this.marketInfo?.team_buy_id || ''
      }
      return fetchPayWay(params).then(data => {
        console.log('hua_bei_installment_select',data.hua_bei_installment_select);
        // 支付方式列表异常
        if (!data.list || !data.list?.length){
          if (this.isRetryPayWay < 3){
            skynet.report({
              details: {
                keyword: 'confirmOrderPage_order_create_fetchPayWay_warning',
                msg: '获取支付方式列表异常捕获异常埋点',
                isRetryPayWay:this.isRetryPayWay,
                data
              },
              level: LogLevel.FATAL,
              type: LogType.CUSTOM
            })
            this.loadingStatus(false);
            this.doValuate(14)
            this.isRetryPayWay ++
          } else {
            this.$toast({
              message: "获取支付列表异常，请稍后重试",
              onClose: () => {
                this.$emit('failCallback')
              }
            });
          }
        }
        this.currencyInfo = data.currency_info ? data.currency_info : {}
        return {
          ways: Array.isArray(data.list) && data.list.length ? data.list : DEFAULT_PAY_WAY,
          huaBeiInstallment: Array.isArray(data.hua_bei_installment_select) ? data.hua_bei_installment_select : [],
          currencyInfo: this.currencyInfo
        }
      }).catch(err => {
        skynet.report({
          details: {
            keyword: 'confirmOrderPage_order_create_fetchPayWay_error',
            msg: '获取支付方式捕获异常埋点',
            err,
            isRetryPayWay:this.isRetryPayWay
          },
          level: LogLevel.FATAL,
          type: LogType.CUSTOM
        })
        // 判断是否支持重试
        if (this.isRetryPayWay < 3){
          this.loadingStatus(false);
          this.doValuate(15)
          this.isRetryPayWay ++
        } else {
          this.$toast({
            message: "获取支付方式异常，请稍后重试",
            onClose: () => {
              this.$emit('failCallback')
            }
          });
        }
        return {
          ways: DEFAULT_PAY_WAY,
          huaBeiInstallment: [],
          currencyInfo:{}
        }
      }).finally(() => {
        this.loadingStatus(false);
      })
    },
    getCanUseVirtual(){
      const {resource_id, resource_type} = this.baseInfoQuery;

      let params = {
        c_user_id: window.USERID,
        app_id: window.APPID,
        resource_id: resource_id,
        resource_type:resource_type
      }
      api.canUseVirtual(params).then((res) => {
        if (res.code === 0) {
          this.supportVirtual = Boolean(res.data.is_ios_coin)

        }
      });
    },
    initBeatApp(){
      let params = {
        c_user_id: window.USERID,
        app_id: window.APPID,
        wallet_type: (isBrandApp && !isIos ) ? 2 : 1,
        pay_way: isELearnApp ? 13 : (!isIos ? 15 : 12)
      }
      this.isLoadedEnd = false
      api.getBlance(params).then((res) => {
        if (res.code === 0) {
          this.isLoadedEnd = true
          this.virtualInfo = res.data
        }
      });
    },
    //获取商家自提状态
    initDeliveryState() {
      api.getDeliveryState({spu_id: this.baseInfo.id}).then((res) => {
        if (res.code === 0) {
          this.isHideSelfPickerInfo = res.data?.is_hide_self_picker_info
          this.showPicker = this.isHideSelfPickerInfo !== 2
          this.userCanPick = res.data.self_service_switch;
        }else{
          skynet.report({details:{
              keyword:'confirmOrderPage_init_delivery_code_error',
              message:"当页支付确认订单异常-获取商家自提状态",
              reportData: res
            },level: LogLevel.FATAL,type: 'CurrentPay'})
        }
      }).catch(err=>{
        skynet.report({details:{
            keyword:'confirmOrderPage_init_delivery_catch_error',
            message:"当页支付确认订单异常-获取商家自提状态",
            reportData: err
          },level: LogLevel.FATAL,type: 'CurrentPay'})
      });
    },
    // 初始化店铺设置信息
    initShopConf() {
      api.getShopConf().then((res) => {
        if (res.code === 0) {
          this.shopConf = res.data;
        }else{
          skynet.report({details:{
              keyword:'confirmOrderPage_init_shop_conf_code_error',
              message:"当页支付确认订单异常-初始化店铺设置信息",
              reportData: res
            },level: LogLevel.ERROR,type: 'CurrentPay'})
        }
      }).catch(err=>{
        skynet.report({details:{
            keyword:'confirmOrderPage_init_shop_conf_catch_error',
            message:"当页支付确认订单异常-初始化店铺设置信息",
            reportData: err
          },level: LogLevel.FATAL,type: 'CurrentPay'})
      });
    },
    initBusinessFeatureConfIfNeed() {
      //线下课才需要请求这个接口
      if(this.baseInfo?.spu_type !== OFFLINE_CLASS) return

      api.getBusinessFeature(this.baseInfo.id).then((res) => {
        if (res.code === 0) {
          this.businessConf = res.data;
        }else{
          skynet.report({details:{
              keyword:'confirmOrderPage_init_business_code_error',
              message:"当页支付确认订单异常-初始化业务特性信息",
              reportData: res
            },level: LogLevel.ERROR,type: 'CurrentPay'})
        }
      }).catch(err=>{
        skynet.report({details:{
            keyword:'confirmOrderPage_init_business_catch_error',
            message:"当页支付确认订单异常-初始化业务特性信息",
            reportData: err
          },level: LogLevel.FATAL,type: 'CurrentPay'})
      });
    },
    // 初始化订单页基本信息
    initConfirmOrderInfo() {
      this.loadingStatus(true);
      let params = {
        spu_id: this.baseInfo.id,
        resource_type: this.baseInfo.resource_type,
        spu_type: this.baseInfo.spu_type,
        address_id: this.addressInfo.id || "",
        sku_id: this.baseInfo.sku || "",
        live_commerce: true
      }

      return request({
        url: `${this.processing}/xe.transaction.order.confirm_detail.get/1.0.0`,
        params
      });
    },
    initFormData() {
      // this.formData.promoCodeInfo = this.baseInfo.promoCode || '';
      this.formData.address = this.addressInfo;
      // this.formData.pickInfo.site = getDataIfWxChannel(KEY_STORAGE_SITE) || this.pickSiteInfo;
    },
    handleGoodsPackageInfo(packageInfo) {
      // 老接口 兼容新组建结构处理
      packageInfo.virtual_num = packageInfo.virtual_goods_num
      packageInfo.entity_num = packageInfo.entity_goods_num

      this.packageInfo = packageInfo;
      if (this.baseInfo.spu_type != "ENT" && packageInfo?.has_package) {
        this.distributionMode = packageInfo.package_delivery;
        if (this.distributionMode === 2) {
          this.activeMode = 2;
        }
      }
    },
    // 处理初始化订单页基本信息
    handleOrderInfo(res) {
      console.log('handleOrderInfo',res);
      if (res.code === 0) {
        this.confirmOrderInfo = res.data;
        if (this.baseInfo.spu_type == "ENT") {
          this.distributionMode = this.confirmOrderInfo.goods_info.distribution_pattern;
          if (this.distributionMode === 2) {
            this.activeMode = 2;
          }
        }
        if(this.baseInfo.spu_type == "COP"){
          this.distributionMode = this.confirmOrderInfo.goods_info.sku_info.distribution_pattern;
          if (this.distributionMode === 2) {
            this.activeMode = 2;
          }
        }
        this.resource_id = this.confirmOrderInfo.goods_info.resource_id;
        if (this.showAddress) {
          this.initAddressErro();
        }
        if (this.confirmOrderInfo.goods_info.sku_info?.sku_floor_price){
          this.sku_floor_price = this.confirmOrderInfo.goods_info.sku_info.sku_floor_price
        }
        if (this.confirmOrderInfo.goods_info.sku_info?.sku_floor_type) {
          this.sku_floor_type = this.confirmOrderInfo.goods_info.sku_info.sku_floor_type
        }
      }else{
        if (res.code === 10086){
          this.isShowGuideLoding = true;
        }
        skynet.report({details:{
            keyword:'confirmOrderPage_init_confirm_order_code_error',
            message:"当页支付确认订单异常-处理初始化订单页基本信息",
            reportData: res
          },level: LogLevel.ERROR,type: 'CurrentPay'})
      }
    },
    initAddressErro() {
      let address_info = this.confirmOrderInfo.address_info;
      console.log('address_info',address_info);
      // 兼容老数据，手机号+区号后格式有误提示用户需要修改
      if (address_info && address_info.currentArea) {
        const patt = /^[1][3-9][\d]{9}/.test(address_info.phone);
        if ((address_info.currentArea.nation_code === '' || address_info.currentArea.nation_code === '86') &&
          (address_info.phone.length != 11 || !patt)) {
          address_info = {
            ...address_info,
            calculate_freight: false,
            calculate_freight_text: '手机号码格式有误，请重新输入'
          }
        }
      }
      let addressInfo = address_info;
      this.addressInfo =
        Array.isArray(addressInfo) || !addressInfo ? {} : addressInfo;
      this.formData.address = this.addressInfo;

    },
    //判断配送模式/信息变化时是否需要触发批价
    shouldValuateOnDeliveryChange(deliveryMode, addressInfo,) {
      switch (deliveryMode) {
        case DELIVERY_MODE.EXPRESSAGE:
          return addressInfo?.id;
        case DELIVERY_MODE.PICK:
          return true;
        default:
          return false;
      }
    },
    // 点击触发地址选择
    onClickAddress() {
      // TODO 点击触发地址选择
      // this.$emit("click-address", this.formData.address);
    },
    // 设置选择的地址信息
    async setAddressInfo(address) {
      this.addressInfo = address
      // let result = await this.initConfirmOrderInfo();
      // this.handleOrderInfo(result);
      // this.doValuate(3);
    },
    /**
     * 地址编辑、删除回调
     * addressInfo：有值为编辑、无值为删除
     */
    async handleAddressCallback(addressInfo = {}) {
      // 判断是否是空地址（删除）
      const emptyAddress = isEmptyObject(addressInfo);
      console.log('emptyAddress',emptyAddress);
      this.setAddressInfo(addressInfo)
      let result = await this.initConfirmOrderInfo();
      this.handleOrderInfo(result);
      this.loadingStatus(false);
      this.doValuate(4);
    },
    getPicker() {
      this.loadingStatus(true);

      getPickerInfo({
        spu_id: this.goodsInfo.spu_id,
        spu_type: this.goodsInfo.spu_type,
      }).then(data => {
        this.formData.pickInfo.picker = data;
        if(data?.lastSelfPickInfo?.place_type === 1){
          this.isPromoterPicksUp = true;
          this.formData.pickInfo.site = data.lastSelfPickInfo;
        }else if(data?.lastSelfPickInfo?.place_name){
          this.formData.pickInfo.site = data.lastSelfPickInfo;
        }else{
          this.formData.pickInfo.site = this.pickSiteInfo;
        }
        // 直播当页支付  - 无需四平好判断
        // setDataIfWxChannel(KEY_STORAGE_PICKER, data);
      }).catch(err => {
        skynet.report({
          details: {
            keyword: 'confirmOrderPage_picker_getPicker_error',
            msg: '获取自提人信息捕获异常埋点',
            err
          },
          level: LogLevel.FATAL,
          type: LogType.HTTP_ERROR
        })
      }).finally(()=>{
        this.loadingStatus(false);
      })

      getPickerList().then(data => {
        this.pickerList = data.list;
      }).catch(err => {
        skynet.report({
          details: {
            keyword: 'confirmOrderPage_picker_getPickerList_error',
            msg: '获取自提人列表捕获异常埋点',
            err
          },
          level: LogLevel.FATAL,
          type: LogType.HTTP_ERROR
        })
      })
    },
    // 设置选择的自提点信息
    setPickSiteInfo(pickSiteInfo) {
      console.log('pickSiteInfo',pickSiteInfo);
      this.pickSiteInfo = pickSiteInfo
    },
    //选择自提人
    handlePickerSelect(picker) {
      this.formData.pickInfo.picker = picker;
      // 直播当页支付 - 无需视频号逻辑
      // setDataIfWxChannel(KEY_STORAGE_PICKER, picker);
      const { address } = this.formData;
      if (this.shouldValuateOnDeliveryChange(this.activeMode, address)) {
        // 触发批价
        this.doValuate(5);
      }
    },
    //选择优惠券/优惠码
    handleCouponChange({ coupons, promoCode }) {
      if (this.valuateData && this.valuateData.price_info && this.valuateData.price_info.final_price == 0){
        try {
          this.$skynet.report({
            details: {
              keyword: 'confirmOrderPage_freePrice_handleCouponChange',
              msg: '0元单再次选择优惠券',
              selectedCoupons: coupons,
              selectedPromoCode:promoCode
            },
            level: LogLevel.INFO,
            type: LogType.CUSTOM,
          })
        } catch (e) {
          console.error(e)
        }
      }
      this.formData.couponInfo = {
        isSelected: true,
        selectedCoupons: coupons
      };
      this.formData.promoCodeInfo = promoCode;
      this.doValuate(6);
    },
    handleIntegralSelectChange(isUseIntegral) {
      this.formData.isUseIntegral = isUseIntegral;
      this.formData.isInitPoint = false;
      this.doValuate(7);
    },
    handleSvipChange(type, trigger) {
      this.formData.identityType = type;
      if (trigger) {
        this.$nextTick(() => {
          this.doValuate(8);
        })
      }
    },
    //信息采集保存后回调
    handleInfoCollectionChange(info) {
      this.formData.infoCollectionInfo = info;
    },
    // 封装批价入参
    assembleValuateParams() {
      // 每次批价时，都重置批价参数
      this.valuateParams = new Parameter();

      const { count, address, identityType } = this.formData;
      const spuId = this.goodsInfo?.spu_id;
      const skuId = this.goodsInfo?.sku_id;
      const { step: teamNum, isSendFriend, isJoin, isFissionPoster } = this.baseInfo;
      const buyNum = count;
      let goodsInfo = [];
      let teamBuyInfo;
      let identityInfo;
      console.log('showAddress',this.showAddress);
      // 地址信息
      const addressId = this.showAddress ? address?.id : 0;

      // 商品信息
      let { activityId, activityType } = this.handleMarketInfo();

      // 直播暂时不支持拼团 - 此处数据缺失（待后续补充）
      // if (activityType == MARKETING_TEAM_BUY && this.goodsInfo?.isTeam) {
      //   let teamBuyTaskId = '';
      //   // 暂时前端转 还是要取后端接口
      //   let teamBuyUserType = isJoin ? 0 : 1
      //   this.baseInfo?.taskId && (teamBuyTaskId = this.baseInfo.taskId);
      //   activityId = this.marketInfo?.team_buy_id;
      //   teamBuyInfo = {
      //     teamBuyUserType,
      //     teamBuyTaskId,
      //     teamNum: teamNum || 1
      //   }
      // }

      let activityInfo;
      if (activityId) {
        //非裂变海报进入的下单，不加活动参数
        if (activityType === MARKETING_FISSION_POSTER && !isFissionPoster) {
          activityInfo = null;
        } else {
          activityInfo = new ActivityInfo(activityId, activityType, teamBuyInfo);
        }
      }

      // 直播口不需要判断购物车
      if (this.isCart) {
        // 针对购物车进入下单页，但是商品已下架情况
        let data = this.cartGoodsList;
        if ((Array.isArray(data) && data.length === 0)) {
          return {};
        }
        goodsInfo = new CartGoodsList(data).transformApiParams()
      } else {
        goodsInfo = new GoodsList({ spuId, skuId, buyNum }, activityInfo).transformApiParams();
      }
      // 身份特权信息
      const realIdentityType = identityType === IdentityType.FORBID_SVIP ? IdentityType.ANSWER : identityType
      identityInfo = new IdentityInfo(realIdentityType).transformApiParams();

      // 优惠券信息
      const { isSelected, selectedCoupons } = this.formData.couponInfo;
      const couponInfoData = new CouponInfo(isSelected, selectedCoupons).transformApiParams();

      // 优惠码信息
      const promoCode = this.formData.promoCodeInfo;
      const promoCodeInfo = new PromoCodeInfo(promoCode).transformApiParams();

      // 积分信息
      const pointsExchange = this.baseInfo.isIntegral;
      const usePoints = this.formData.isUseIntegral;
      const pointInfo = new PointInfo(pointsExchange, usePoints,0,this.formData.isInitPoint).transformApiParams();

      // 会员等级
      const isUseMemberLevel =  this.formData?.isUseMemberLevel === undefined ? 1 : this.formData?.isUseMemberLevel
      console.log('isUseMemberLevel-----', this.formData?.isUseMemberLevel );
      const level_member_info = new LevelMemberInfo(isUseMemberLevel).transformApiParams()

      // 虚拟币信息

      // 是否为社群续费
      const communityRenewal = this.goodsInfo?.spu_type === ASSOCIATION && this.baseInfo?.renew == '1';


      // 将批价所有参数封装进一个对象中
      addressId && this.valuateParams.append('address_id', addressId);
      this.valuateParams
        .append('identity_info', identityInfo)
        .append('goods_list', goodsInfo)
        .append('points_info', pointInfo)
        .append('community_renewal', communityRenewal)
        .append('coupon_info', couponInfoData)
        .append('promo_code_info', promoCodeInfo)
        .append('from_shopping_cart', false)  // 直播不存在购物车 - 写死false
        .append('is_gift', false)  // 直播不存在赠送 - 写死false
        .append('level_member_info', level_member_info);
      return this.valuateParams;
    },
    /**
     * 触发批价
     * @description 触发批价的场景
     * 1、切换数量
     * 2、初始化
     * 3、选择地址信息
     * 4、地址编辑、删除回调
     * 5、选择自提人
     * 6、选择优惠券/优惠码
     * 7、选择积分
     * 8、选择Svip
     * 9、下单前校验批价
     * 10、切换配送方式
     * 11、地址监听（兜底）
     * 12、自提监听
     * 13、领取优惠卷重新批价
     * 14、支付方式异常 - 重试
     * 15、支付方式接口失败 - 重试
     * @param entrance 入口
     */
    async doValuate(entrance){
      console.log('entrance=>',entrance, this.showLoadingE);
      if (this.showLoadingE && entrance !== 1) {
        return;
      }
      this.loadingStatus(true);

      // 批价
      const params = this.assembleValuateParams();

      if (isEmptyObject(params)) {
        this.loadingStatus(false);
        return;
      }

      // 商品参数校验
      if (params && params.goods_list){
        let missingParameter = false;
        params.goods_list.forEach(val=>{
          if (!val.spu_id || !val.sku_id){
            missingParameter = true
          }
        })
        if (missingParameter) {
          console.log('批价参数校验失败',params)
          this.loadingStatus(false);
          return;
        }
      }else{
        this.loadingStatus(false);
        return;
      }

      // 当是初始请求批价时，触发帮领取优惠券
      if (entrance === 2) {
        try {
          await this.autoReceiveCoupon()
        }catch (e){
          console.log('领取优惠券失败')
        }
      }
      params.live_commerce = true
      return valuate(params).then(async (res) => {
        this.valuateData = res;
        this.memberLevelInfo = res.level_member_info || {}
        this.allData = res.points_info.deduct_rule;
        if (sessionStorage.getItem("toastWarn")) {
          this.$toast(this.t('confirmOrder_order_purchase_pieces'));
          setTimeout(() => {
            sessionStorage.removeItem("toastWarn");
          }, 3000);
        }
        if(!this.zeroPay){
          // 获取支付方式
          const {ways,huaBeiInstallment} = await this.initPayway(this.valuateData.token);
          this.payWayList = ways;
          this.huaBeiInstallment = huaBeiInstallment;
          let payWay = ways[0].pay_way;

          if (ways.length > 1) {
            //查找默认支付方式
            for (const ways_index in ways ) {
              if (ways[ways_index]?.is_default == 1) {
                console.log(123,ways[ways_index].pay_way);
                payWay = ways[ways_index].pay_way;
              }
            }
          } else if (ways.length == 1) {
            payWay = ways[0].pay_way
          }

          // 本地支付方式缓存
          var payWayLocalCache = localStorage.getItem('payWay');
          if (payWayLocalCache) {
            for (const ways_index in ways ) {
              if (ways[ways_index].pay_way == payWayLocalCache) {
                payWay = Number(payWayLocalCache);
                if (payWay === 14){
                  try {
                    var InstallmentInfo = localStorage.getItem('InstallmentInfo');
                    if (InstallmentInfo) {
                      this.huabeiParams = JSON.parse(InstallmentInfo)
                    }
                  } catch (e) {
                    console.error(e)
                  }
                }
              }
            }
          }

          this.payWay = payWay
        }
        this.isShowGuideLoding = false;
      }).catch(err => {
        const { code, msg, res, response } = err || {};
        if (entrance === 2){
          skynet.report({details:{
              keyword:'confirmOrderPage_init_valuate_error',
              message:"当页支付首次批价错误日志", reportData: err},level: LogLevel.ERROR,type: 'CurrentPay'})
        }
        if (entrance === 2 && code === 10086) {
          this.isShowGuideLoding = true;
        }else if(msg){
          Toast(msg)
        }
      }).finally(() => {
        this.loadingStatus(false);
        // 神策上报
        this.trackEvent();
        // 初次批价&开了信息采集&信息采集接口还没返回
        if(this.waitInformation && this.assertNeedCollectInfo?.is_gray === true){
          this.loadingStatus(true)
          this.setTime = setTimeout(() => {
            this.loadingStatus(false)
            this.waitInformation = false
          }, 2000);
        }
      })
    },
    async submitOrder() {
      // 直播不需要支付前电子合同

      sensorsTrackButton({
        page_id: "C#h5#alive#alive_room",
        l_program: "H5",
        page_name: "直播间页面",
        page_path: "C端#H5#直播#直播间页面",
        page_button: "提交订单",
        app_id: window.APPID,
        c_user_id: window.USERID,
        client: window.wx?.CLIENT_SYSTEM,
        goods_id: this.goodsInfo?.spu_id,
        cu_id:this.cu_id,
        resource_id: this.baseInfoQuery.resource_id,
        cmm2: window.isQlive ? '企业直播' : '知识店铺'
      })
      // 兼容外部app拉起支付回到支付页没有弹窗 又去点击下单 此时提交按钮再次校验是否有上次未完成订单
      this.$emit('checkOrderState', 2);

      // 本期不涉及小程序 后续迭代需补充 - 小程序SDK一期，不支持支付
      // if (!PayControl.getPayStatusInMiniprogramSdk(this.miniprogramSdkPaySetting?.paymentSwitch, this.isIntegral)) {
      //   Toast('小程序暂不支持支付')
      //   return
      // }

      //如果没有批价成功，则先批价再下单
      if (isEmptyObject(this.valuateData)) {
        const isSucceed = await this.doValuate(9);
        if (!isSucceed) return;
      }

      //校验表单参数
      const valid = await this.validateForm();
      if (!valid) return;

      try{
        if(this.assertNeedCollectInfo.is_gray && this.assertNeedCollectInfo.need_collect && this.infoIsLoadSuc && this.needCollect){
          //在白名单内，js还未加载完，必须等待信息采集加载完才给下单
          if(isEmptyObject(this.formData.infoCollectionInfo)){
            this.$toast('下单失败，未填写信息采集，请重新提交订单');
            return
          }
        }
      }catch(err){
        console.log(err)
      }

      //组装下单参数
      const orderParams = this.assembleCreateOrderParams()

      if (isEmptyObject(orderParams)) {
        return;
      }
      let payWay = DEFAULT_PAY_WAY[0].pay_way;
      let InstallmentInfo = this.huabeiParams // 花呗支付信息
      payWay = this.payWay;
      if(isEcommunityApp){ //圈子app 支付方式
        payWay = this.virtualPayWay;
        InstallmentInfo = this.huabeiParams;
      }
      orderParams.append('pay_way', payWay);
      // 缓存支付方式
      localStorage.setItem('payWay', payWay);

      if(payWay === 14){ //花呗支付的话需要传花呗分期数、免息
        try{
          localStorage.setItem('InstallmentInfo', JSON.stringify(InstallmentInfo));
        }catch (e) {
          console.error(e)
        }
        orderParams.append('installment', InstallmentInfo.installment);
        orderParams.append('is_interest_free', InstallmentInfo.isInterestFree);
        orderParams.append('installment_activity', InstallmentInfo.installmentActivity);
      }
      if(payWay === 16){
        const aliveUrl = window.location.href;
        const orderId = ''//paypal下发空的orderId
        const jumpData = getJumpUrls(this.baseInfo, this.goodsInfo, this.marketInfo, window.USERID, orderId, false, '');
        const { paySuccessUrl } = jumpData;
        orderParams.append('redirect_url', `https://${window.APPID}.h5.xiaoeknow.com${paySuccessUrl}&aliveBackUrl=${aliveUrl}`);
        orderParams.append('cancel_url', aliveUrl);
      }
      try {
        // 针对UA问题，新增微信环境判断
        if(WeixinJSBridge && typeof WeixinJSBridge === 'object' && typeof WeixinJSBridge.invoke === 'function'){
          orderParams.append('user_agente_env_type', 'WeChatH5')
        }
      } catch (error) {
        console.error(error)
      }
      await this.createOrderFun(orderParams)
    },
    //下单前校验
    validateForm() {

      const descriptor = {
        address: new AddressRule(this.showAddress),
        pickInfo: new PickInfoRule(this.showPickSelect, this.isHideSelfPickerInfo),
        // 信息采集
        infoCollectionInfo: new InfoCollectionRule(this.showInfoCollection, this.$refs['info-collect']),
        // 线下课
        eduInfo: new OfflineClassRule(this.showOfflineClass, this.$refs['offline-class']),
        // 活动报名 - 直播需暂时不需要
        // activityApplyInfo: new ActivityApplyRule(false, this.$refs['activity-apply'])
      }

      console.log('descriptor',descriptor);
      console.log('this.formData',this.formData);

      return new Schema(descriptor).validate(this.formData).catch(({ errors }) => {
        console.log(errors);
        const message = errors[0];
        this.$toast(message);
        return false;
      });
    },
    assembleCreateOrderParams() {
      // 取至路由
      const { isSendFriend, isIntegral: pointsExchange, shareType, shareUserId, commonAuthCode, step: teamNum, isTeam, isCart, isJoin, aliveId, communityIdWindow, communityApplyId, adType, xiaoeCampBusinessAppId, channelId } = this.baseInfo;
      // 取至 formData
      const { isSelected, pickInfo, invoiceInfo, infoCollectionInfo, eduInfo, userRemark, activityApplyInfo, promoCodeInfo: promoCode } = this.formData
      //取至批价返回数据
      const { token, identity_info, coupon_info, points_info, goods_list } = this.valuateData
      const addressId = this.activeMode === DELIVERY_MODE.EXPRESSAGE ? (this.valuateParams?.address_id || this.formData.address?.id || 0) : 0
      const siteId = pickInfo?.site?.place_id || 0
      const pickerId = this.isHideSelfPickerInfo === 2 ? 0 : (pickInfo?.picker?.id || 0)
      const place_type = pickInfo?.site?.place_type || 0

      const extendObjectInfo = {
        activity_manager: activityApplyInfo,
        student_info: eduInfo,
        info_collect_object_info: infoCollectionInfo,
        training_camp: {
          xiaoe_camp_business_app_id: xiaoeCampBusinessAppId || ''
        }
      }
      const miscParameter = new MiscParameter(isSendFriend, shareType, shareUserId, commonAuthCode);
      // 商品信息
      let orderGoodsList = [];
      if (this.isCart) {
        // 针对购物车进入下单页，但是商品已下架情况
        let data = this.cartGoodsList;
        if (Array.isArray(data) && data.length === 0) {
          return {};
        }
        orderGoodsList = new CartGoodsList(data).transformApiParams()
      } else {
        orderGoodsList = new GoodsOrderList(goods_list, isTeam, teamNum, isJoin).transformApiParams();
      }
      // 身份信息
      const identityType = identity_info?.identity_type;
      const realIdentityType = identityType === IdentityType.FORBID_SVIP ? IdentityType.NONUSE : identityType
      const identityInfo = new IdentityInfo(realIdentityType).transformApiParams();
      // 优惠券
      const couponInfo = new CouponInfo(isSelected, coupon_info?.selected_coupons?.list).transformOrderParams();
      // 优惠码
      // 兼容优惠码不可用，url上带了优惠码
      // 通过批价接口处理优惠码，如果优惠码不可用，promo_code_info.can_use_promo_code字段为false
      let promoCodeInfo = new PromoCodeInfo(promoCode).transformApiParams();
      if (this.valuateData && this.valuateData.promo_code_info && this.valuateData.promo_code_info.can_use_promo_code === false) {
        promoCodeInfo.promo_code = '';
      }
      // 积分信息
      const { is_use_integral, used_point } = points_info;
      const pointInfo = new PointInfo(!!pointsExchange, !!is_use_integral, used_point || 0).transformCreateOrderParams();
      // 地址、自提相关信息
      const deliveryInfo = new DeliveryInfo(this.activeMode, addressId, pickerId, siteId, place_type).transformApiParams();
      //渠道来源
      const { channelType, channelBusId } = resolveChannelInfo(aliveId, adType, communityIdWindow, communityApplyId, channelId);

      // 会员等级
      const isUseMemberLevel =  this.formData?.isUseMemberLevel === undefined ? 1 : this.formData?.isUseMemberLevel
      const level_member_info = new LevelMemberInfo(isUseMemberLevel).transformApiParams()
      // 终端标识
      const miniProType = getMiniProType(this.isSupportCoin);

      const queryString = window.location.search; // 获取 URL 的查询部分
      const params = new URLSearchParams(queryString);

      const queryChannelId = params && params.get('channel_id'); // 获取 'channel_id' 参数

      // 页面统计id
      const merchantUrlId = channelId || queryChannelId || '';

      // 订单类型 普通订单-1，积分兑换-4
      const tradeType = this.isIntegral ? 4 : 1;

      return new Parameter(miscParameter.transformApiParams()) //路由上的一些参数
        .append('token', token) // 批价token
        .append('goods_list', orderGoodsList) // 商品信息
        .append('identity_info', identityInfo) //身份信息
        .append('promo_code_info', promoCodeInfo) //优惠码
        .append('coupon_info', couponInfo) //优惠券
        .append('points_info', pointInfo) //积分信息
        .append('invoice_info', invoiceInfo) //发票信息
        .append('delivery_object_info', deliveryInfo) // 地址、字提人信息
        .append('extend_object_info', extendObjectInfo) //活动管理的学生信息  线下课学生信息  小鹅通训练营订购商家APPID
        .append('user_remark', userRemark) // 留言
        .append('channel_bus_id', channelBusId) // 渠道id
        .append('channel_type', channelType) //渠道类型
        .append('from_shopping_cart', isCart) //是否是购物车
        .append('mini_pro_type', miniProType) //终端标识
        .append('merchant_url_id', merchantUrlId) // 页面统计id
        .append('trade_type', tradeType) // 订单类型
        .append('level_member_info', level_member_info); //等级会员
    },
    //下单
    createOrderFun(orderParams) {
      // 新loading
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: this.t('payModule_on_sale'),
      });
      // if(this.useScatter){
      //   this.isFullScreen = true;
      //   this.loadingText = this.t('payModule_on_sale');
      // }else{
      //   this.isFullScreen = false;
      //   this.loadingText = '';
      // }
      // this.createOrderloading = true;
      // 下单前打散
      if (this.useScatter){
        if (this.createTimer){
          clearTimeout(this.createTimer)
        }
        this.createTimer = setTimeout(()=>{
          return this.createOrder(orderParams)
        },this.generateRandomMilliseconds(0,5))
      }else{
        return this.createOrder(orderParams)
      }
    },
    createOrder(orderParams){
      // 注意：直播走特殊下单接口 - 后续复用次代码需使用老方法createOrder
      return createOrderInLive(orderParams).then(async (data) => {
        // this.createOrderloading = false;
        // 新loading
        this.$toast.clear()
        this.payResult = data
        const orderId = data.order_id;
        console.log('this.payResult',this.payResult);
        const subOrders = JSON.stringify(data.order_id_list)
        sessionStorage.setItem(SUB_ORDERS, subOrders)
        this.jumpData = getJumpUrls(this.baseInfo, this.goodsInfo, this.marketInfo, window.USERID, orderId, false, '');
        // 0元订单处理：不再拉起微信支付
        if (data.order_pay_status === ORDER_PAY_STATUS.PAID) {
          this.$emit('successCallback',this.payResult)
          return;
        } else {
          // 非0元单、非购物车、非微信小程序才校验电子合同
          //   if (!this.isCart && !inMiniprogram) {
          //     // 根据resource_id查询商品是否开启支付前签署电子合同
          //     await this.getContract([this.goodsInfo?.resource_id]);
          //     // 商品开启了支付前签署电子合同
          //     if (this.contractData?.[this.goodsInfo?.resource_id]?.sign_step === 'BEFORE_PAY') {
          //       const resultData = await getSignUrl({
          //         order_id: orderId
          //       })
          //       if (resultData?.[0]?.sign_url?.person_url) {
          //         this.personUrl = resultData?.[0]?.sign_url?.person_url;
          //         this.isShowContract = true;
          //         return false;
          //       }
          //     }
          //   }

          this.doPay(data);
        }
      }).catch(err => {
        console.log(err);
        const { code, msg, data, res, response } = err || {};
        // code 10086 网关限流 - 提示用户
        if(code === 10086 && this.useScatter){
          setTimeout(()=>{
            // 新loading
            this.$toast.clear()

            this.$nextTick(()=>{
              this.$toast(this.t('confirmOrder_busy'));
            })
          },this.generateRandomMilliseconds(0,3))
        }else if (code === 10086){
          // 新loading
          this.$toast.clear()
          this.$toast(this.t('confirmOrder_busy'));
        }else{
          // 新loading
          this.$toast.clear()
        }

        // 接口404情况（比如不在灰度中）
        if (this.interfaceNotExist(res, response)) {
          return true;
        }

        if (code === CREATE_ORDER_CODE.GOODS_DELETED1 || code === CREATE_ORDER_CODE.GOODS_DELETED2) {
          this.$toast({
            message: msg || "商品已删除",
            onClose: () => {
              this.$emit('failCallback')
            }
          });
        } else if(code === CREATE_ORDER_CODE.DELIVERY_CHANGE) {
          //修改了配送方式，需要刷新页面
          this.$toast({
            message: msg || "配送方式已改变，请重新选择",
            onClose: () => {
              this.$emit('failCallback')
            }
          });
        }  else if(code === CREATE_ORDER_CODE.GOODS_DELETED3) {
          //修改了配送方式，需要刷新页面
          this.$toast({
            message: msg || "自提信息已更新，请重新选择",
            onClose: () => {
              this.$emit('failCallback')
            }
          });
        } else {
          this.$toast(msg || "下单接口返回异常，请稍后重试");
        }
        console.error(err);
        this.payResult = err;

        //下单请求code!==0的异常已经在createOrder方法内上报了，这里只做非请求的异常上报，避免重复上报的情况
        if (typeof code !== 'number') {
          this.$skynet.report({
            details: {
              keyword: 'confirmOrderPage_order_create_error',
              msg: '下单异常捕获异常埋点',
              req: {
                method: "POST",
                params: orderParams,
              },
              res: orderParams,
              err
            },
            level: LogLevel.FATAL,
            type: LogType.CUSTOM,
          });
        }
      })

    },
    // 生成一个介于minSeconds到maxSeconds之间的随机毫秒数
    generateRandomMilliseconds(minSeconds = 0, maxSeconds = 3) {
      const minMilliseconds = minSeconds * 1000; // 将最小秒数转换为毫秒
      const maxMilliseconds = maxSeconds * 1000; // 将最大秒数转换为毫秒
      // 生成随机毫秒数
      return Math.floor(Math.random() * (maxMilliseconds - minMilliseconds + 1)) + minMilliseconds;
    },
    //支付
    doPay(data) {
      //确定支付方式
      const { need_jump: needJump, pay_config: payConfig } = data;
      const { pay_way, pay_type, pay_tab } = payConfig;
      const payType = this.getCurrentPayWayName(pay_way, pay_type, pay_tab, needJump)
      //组装对应参数
      const { goods_name, spu_id } = this.goodsInfo;
      const payInfoObj = producePayParams(payType, data, this.jumpData, goods_name, this.ratePrice, spu_id, this.baseInfo.isTeam)
      //缓存数据
      const { paySuccessUrl, payFailUrl } = this.jumpData;
      if (payType === PAY_WAY.WxH5Pay || payType === PAY_WAY.AliPay) {
        setOrderCache(paySuccessUrl, payFailUrl, data);
      }

      //具体支付策略
      let payStrategy;
      console.log('payType',payType);
      if (isAliveIframe && IFRAME_SPECIAL_PAY[payType]) {
        payStrategy = getspecialByType(payType);
      } else {
        payStrategy = getPaymentByType(payType);
      }

      // 跳转支付空白页上报
      if (payType == PAY_WAY.H5BlankPay) {
        this.$skynet.report({
          details: {
            keyword: 'confirmOrderPage_order_pay_H5BlankPay',
            msg: '跳转支付空白页上报日志',
            payInfoObj
          },
          level: LogLevel.INFO,
          type: LogType.CUSTOM
        })
      }


      //实施对应支付策略
      payStrategy.pay(payInfoObj).then(() => {
        switch (payType) {
          case PAY_WAY.AliPayCommand:
            this.handleAliPay()
            break;
          case PAY_WAY.VirtualPay:
          case PAY_WAY.WxJSAPIPay:
            this.handlePayBack(data);
            break;
          case PAY_WAY.AliPay:
          case PAY_WAY.AliHuabeiPay:
          case PAY_WAY.H5BlankPay:
          case PAY_WAY.WxH5Pay:
          case PAY_WAY.PayPal:
            break;
          default:
            return Promise.reject({
              errMsg: "未知支付类型",
              info: {
                pay_way,
                pay_type,
                pay_tab,
                needJump,
                payType
              }
            });
        }
      }).catch((err) => {
        this.handlePayBack(data);
        //埋点错误日志
        this.$skynet.report({
          details: {
            keyword: "confirmOrderPage_order_pay_error",
            msg: "支付回调捕获异常埋点",
            err,
            payType,
            payWay: pay_way
          },
          level: LogLevel.FATAL,
          type: LogType.CUSTOM
        })
      });
    },
    handleAliPay() {
      const payConfig = {
        ...this.payResult?.pay_config,
        order_id: this.payResult?.order_id
      }
      new CopyPasswordDialog(payConfig, this.$refs.orderBarRef.getFinalPrice()).perform();
      const params = {
        page_id: "goods#open_alipay_zhi",
        platform: "h5",
        l_program: "knowledge_shop",
        app_id: window.APPID,
        c_user_id: window.USERID,
        union_id: ""
      }
      try {
        window.sensors.track('view_page', params);
      } catch (error){
        console.log(error)
      }
    },
    handlePayBack(order) {
      // const { paySuccessUrl, payFailUrl } = this.jumpData;
      new PayBackHandler(false, false, order, true).perform().then(()=>{
        this.$emit('successCallback',this.payResult)
      }).catch(err => {
        this.$emit('failCallback')
      })
    },
    getCurrentPayWayName(payWay, payType, payTab, needJump) {
      //快手小程序
      if (isKSMiniProgram) {
        return PAY_WAY.KSMiniProgramPay
      }
      //店铺小程序、鹅圈子小程序、独立圈子小程序、视频号小程序、视频号分销小程序支付
      if (isMiniEnv()) {
        return PAY_WAY.MpBlankPay
      }
      //吱口令,优先级高，有同时花呗分期、吱口令的情况
      if (payTab === PAY_TAB_LIST.ZFB_ZKL) {
        return PAY_WAY.AliPayCommand
      }
      //支付宝支付
      if (payWay === PAY_WAY_LIST.ALI_PAY) {
        return PAY_WAY.AliPay
      }
      //花呗支付
      if(payWay === PAY_WAY_LIST.ALI_HUABEI_PAY){
        return PAY_WAY.AliHuabeiPay
      }
      //paypal支付
      if(payWay === PAY_WAY_LIST.PAYPAL){
        return PAY_WAY.PayPal
      }
      if ((payWay === PAY_WAY_LIST.WEIXIN_PAYMENT || payWay === PAY_WAY_LIST.WECHAT_PAY) && payType === PAY_TYPE_LIST.H5 && needJump != 1) {
        return PAY_WAY.WxJSAPIPay
      }
      //
      if ((payWay === PAY_WAY_LIST.WEIXIN_PAYMENT || payWay === PAY_WAY_LIST.WECHAT_PAY) && payType === PAY_TYPE_LIST.APP_H5) {
        return PAY_WAY.WxH5Pay
      }
      // 印象虚拟币支付
      if (payWay === PAY_WAY_LIST.YX_VIRSUAL_PAY && enableAppPayment) {
        return PAY_WAY.VirtualPay
      }
      // 跳空白页支付
      if (needJump == 1) {
        return PAY_WAY.H5BlankPay
      }
      return PAY_WAY.WxJSAPIPay
    },
    // 接口404情况（比如不在灰度中）
    interfaceNotExist(res, response) {
      if (typeof res === "object" || typeof response === "object") {
        const status = res?.response?.status;
        const reqStatus = response?.status;
        if (status == 404 || reqStatus == 404) {
          this.$toast({
            message: "支付环境已更新，请重新下单",
            duration: 2000,
            onClose: () => {
              this.$emit('failCallback')
            }
          });
          return true;
        }
      }
      return false;
    },
    // 处理批价的 activity_type 和 activity_id
    handleMarketInfo() {
      let { activity_id: activityId, activity_type: activityType, event_has_stock, in_activity } = this.marketInfo;
      let isShield = activityId ? SHIELD_ACTIVITY.some(item => activityId.includes(item)) : false;
      if ((activityType === MARKETING_SEC_KILL && (event_has_stock === 0 || in_activity === 0)) || isShield) {
        return {};
      }
      return {
        activityId,
        activityType
      }
    },
    changePayWayHuabei(val){
      this.huabeiParams = val
    },
    // 切换快递、自提配送方式
    changeMode: debounce(async function (mode) {
      this.activeMode = mode;
      const { address } = this.formData;
      if (this.shouldValuateOnDeliveryChange(mode, address)) {
        // 触发批价
        this.doValuate(10);
      }
    }, 1000, { leading: true }),
    // 重置data里某些值
    resetData() {
      // TODO 重置data里某些值
    },
    handleOrderBarShow(val){
      this.orderBarShow = val
    },
    trackEvent() {
      try {
        let { isEnterpriseLive } = this;
        let cu_id = ''
        let coupon_info = this.valuateData?.coupon_info
        if (coupon_info?.selected_coupons && coupon_info.selected_coupons.list && coupon_info.selected_coupons.list.lenght !== 0){
          cu_id = coupon_info.selected_coupons.list[0].cu_id
          this.cu_id = cu_id
        }

        if (isEnterpriseLive) {
          let qLiveSensorsData = JSON.parse(
            sessionStorage.getItem("qLiveSensorsData") || "{}"
          );
          let page_id = "C#qy_alive#h5#goods#confirm_order";
          let page_path = "C端#企业直播#H5#商品#确认订单页";
          let l_program = "企业直播";
          let {
            aliveId,
            from_share = 0,
            share_user_id = "",
            cmm6 = 0,
          } = qLiveSensorsData;
          let goodsSourceMap = {
            0: "其他",
            1: "卡片",
            2: "购物车",
          };
          // 神策埋点
          sensorsViewPage({
            page_id,
            page_path,
            l_program,
            goods_id: this.baseInfo.id,
            spu_type: this.baseInfo.spu_type,
            cu_id,
            p_price: this.valuateData.price_info?.final_price,
            from_share: Number(from_share),
            sharer_id: share_user_id,
            resource_id: aliveId, // 直播间id
            c_user_id: window.USERID,
            cmm1: this.baseInfo.cart ? "是" : "否",
            cmm2: '',
            cmm6: goodsSourceMap[cmm6],
            // 微信落地页埋点预留
            cmm3: "",
            cmm4: "",
            cmm5: "",
          });
        } else {
          sensorsViewPage({
            goods_id: this.baseInfo.id,
            spu_type: this.baseInfo.spu_type,
            cu_id,
            p_price: this.valuateData.price_info?.final_price,
            cmm1: this.isCartTemp ? "是" : "否",
            cmm2: '',
          });
        }
      } catch (error) {
        console.log('trackEvent',error);
      }
    },
    // 信息采集上报
    infoCollectionReport(isLoad = true){
      const info = {
        initTimestamp: this.infoCollectionLoaded.join(","),
        keyword: 'confirmOrderPage_collect_JStimestamp',
        msg: '信息采集组件JS资源监控埋点',
        createOrderTime: new Date().getTime(),
        isGray: this.assertNeedCollectInfo.is_gray,
        collectSwitch: this.assertNeedCollectInfo.need_collect,
        isLoad
      }
      console.log("info",info)
      this.$skynet.report({
        details: info,
        level: LogLevel.INFO,
        type: LogType.CUSTOM,
      });
    },
    //修改会员等级使用状态
    handleMemberDiscount(val){
      this.formData.isUseMemberLevel = val;
      this.$nextTick(() => {
        this.doValuate();
      })
    }
  },
  watch:{
    marketingData: {
      handler(marketingData) {
        this.marketingDataLoaded = true;
      }
    },
    baseInfo: {
      handler: function(newV, oldV) {
        this.$emit("update:baseInfoQuery", newV);
      },
      deep: true,
    },
    boxshow: {
      handler: function(value) {
        if (!value) {
          this.resetData();
        }
        this.showPopup = value;
      },
    },
    showAddress(val) {
      if (val) {
        this.initAddressErro();
      }
    },
    addressInfo: {
      handler: async function (newVal, oldVal) {
        if (!newVal?.id) {
          this.formData.address = null;
        } else {
          this.formData.address = newVal;
        }
        // id发生变化时，触发批价
        if (newVal?.id && newVal?.id != oldVal?.id) {
          console.log('addressInfo newVal>',newVal);
          console.log('addressInfo oldVal>',oldVal);
          const { address } = this.formData;
          if (this.shouldValuateOnDeliveryChange(this.activeMode, address)) {
            this.$nextTick(async () => {
              // 购物车下单，切换地址，要查询商品在该地址是否可以购买
              let result = await this.initConfirmOrderInfo();
              this.handleOrderInfo(result);
              this.loadingStatus(false);
              await this.doValuate(11);
            })
          }
        }
      },
      deep:true
    },
    activeMode: {
      handler: function (val) {
        sessionStorage.setItem(KEY_STORAGE_DELIVERY_MODE, val)
        if (val === DELIVERY_MODE.PICK) {
          this.getPicker();
        }
      },
      immediate: true
    },
    //监听自提点变化
    pickSiteInfo: {
      handler: function (val) {
        this.formData.pickInfo.site = getDataIfWxChannel(KEY_STORAGE_SITE) || val;
        const { address } = this.formData;
        if (this.shouldValuateOnDeliveryChange(this.activeMode, address)) {
          // 触发批价
          this.doValuate(12);
        }
      }
    },
    invalidAddress: {
      handler: function (val) {
        this.isCreateOrderDisabled = val
      },
      immediate: true
    },
  }
}
</script>

<template>
  <div class="content">
    <!-- 如果批价异常、超时、限流，显示引导刷新加载组件 -->
    <GuideLoading v-if="isShowGuideLoding" @onRefresh="onRefresh" @refresh-exceed="onRefreshExceed"></GuideLoading>
    <div v-else>
      <!-- loading组件 -->
      <loading
        v-if="showLoadingE || createOrderloading"
        :fullscreen="isFullScreen"
        :text="loadingText"
        :class="{'custom-loading': isFullScreen}"
        style="position: fixed"
      >
      </loading>
      <!-- 配送模式选择 商品自提/快递配送 -->
      <ModeSelect v-if="showMode" :mode="activeMode" @change="changeMode" :customDeliveryType="customDeliveryType" :btnBg="'#f5f5f5'" class="bg-white"></ModeSelect>
      <!-- 地址选择 -->
      <Address v-if="showAddress" ref="address-info" :addressInfo="addressInfo" :address="formData.address" :openNewPop="false" :isCart="false"
               :invalidAddress="invalidAddress" @click="onClickAddress" @setAddressInfo="setAddressInfo"
               @handleAddressCallback="handleAddressCallback">
      </Address>
      <!-- 自提信息选择 -->
      <PickupSelect v-if="showPickSelect" ref="pick-info" :pick-info="formData.pickInfo" :picker-list="pickerList" :openNewPop="false" :isPromoterPicksUp="isPromoterPicksUp"
                    :showPicker="showPicker"              
                    @picker-select="handlePickerSelect"
                    @setPickSiteInfo="setPickSiteInfo" @getPicker="getPicker">
      </PickupSelect>
      <!-- 商品信息 -->
      <GoodsInfo :baseInfo="baseInfo" :goodsInfo="goodsInfo" :cartGoodsList="cartGoodsList"  :marketingData="marketInfo" :spu-info="goodsInfo"
                 :periodIsGray="isCoursePeriodGray" :formData="formData" :isCart="isCartTemp"  :svipInfo="superVipInfo" :confirmDetail="confirmOrderInfo"
                 :businessConf="businessConf" :packageInfo="packageInfo" @count-change="onCountChange">
      </GoodsInfo>
      <!-- 优惠券/码/积分/超级会员 -->
      <div class="coupon-integral-wrapper">
        <!-- 【营销】优惠券/码展示 -->
        <CouponShow v-if="showCoupon" :isCart="baseInfo.isCart" :formData="formData" :goodsInfo="goodsInfo"
                    :baseInfo="baseInfo" :valuateData="valuateData" :marketingData="marketInfo" @change="handleCouponChange">
        </CouponShow>
        <div v-if="sku_floor_type == 2" class="couponTip"> 提示：本单商家设置优惠券最高抵扣{{ (this.sku_floor_price / 100).toFixed(2) }}元 </div>

        <!-- 积分组件 -->
        <IntegralSelect
          v-if="showIntegral"
          :allData="allData"
          :valuateData="valuateData"
          :resourceType="goodsInfo.resource_type"
          @change="handleIntegralSelectChange"/>

        <!-- 选择是否使用超级会员 -->
        <SvipSelect v-if="showSvip" :discount-info="svipDiscount" @change="handleSvipChange"></SvipSelect>
      </div>
      <!-- 信息采集 -->
      <InfoCollectionWrapper v-if="showInfoCollection" ref="info-collect" :resource-id="goodsInfo.resource_id"
                             :resource-type="goodsInfo.resource_type" @change="handleInfoCollectionChange">
      </InfoCollectionWrapper>
      <!-- 会员等级 -->
      <MemberLevel
        v-if="showMemberLevel"
        :memberLevelInfo="memberLevelInfo"
        @change="handleMemberDiscount"
      />
      <!-- 发票 -->
      <InvoiceShow v-if="showInvoice" v-model="formData.invoiceInfo" :shopConf="shopConf"></InvoiceShow>
      <!-- 留言 -->
      <LeaveWord v-model="formData.userRemark"></LeaveWord>
      <!-- 支付明细 -->
      <pay-detail v-if="showPayDetail" :valuateData="valuateData" :cartGoodsList="cartGoodsList" :goodsInfo="goodsInfo" :activeMode="activeMode"
                  :distributionMode="distributionMode" :isIntegral="this.baseInfo.isIntegral" :baseInfo="baseInfo" :count="formData.count">
      </pay-detail>

      <!-- 支付方式 -->
      <div class="pay-way-card"
           v-if="payWayList.length && !showRecharge && !showRechargeCircle">
        <div data-v-5eebc3fb="" class="pay-name font">支付方式</div>
        <PayWay class="pay-way-module"
                :ways="payWayList"
                :huaBeiInstallment="huaBeiInstallment"
                :payWay.sync="payWay"
                @changePayWayHuabei="changePayWayHuabei"></PayWay>
      </div>

      <!-- 提交订单按钮 -->
      <OrderBar
        v-show="orderBarShow"
        ref="orderBarRef"
        @submitOrder="submitOrder"
        :disabled="isCreateOrderDisabled"
        :deliveryMode="activeMode"
        :isIntegral="baseInfo.isIntegral"
        :valuateData="valuateData"
        :baseInfo="baseInfo"
        :currencyInfo='currencyInfo'
        :count="formData.count"
        :payWay="payWay"
        :virtualInfo="virtualInfo">
      </OrderBar>
    </div>


  </div>
</template>

<style scoped lang="scss">
::v-deep .bg-white{
  background-color: #fff;
}
.coupon-integral-wrapper {
  margin-bottom: 0.18rem;
}

.couponTip {
  font-size: 0.27rem;
  color: #ff821f;
  padding: 0.2rem;
  padding-left: 0.3rem;
}
.pay-way-card{
  margin-top: 0.18rem;
  box-sizing: border-box;
  padding: 0.32rem 0.32rem 0.16rem;
  background: #fff;
  .virtual-info .font{
    font-size: 0.28rem;
    color: #333333;
    font-weight: 500;
  }
}
</style>
<style lang="scss">
// 自定义全局loading样式
.custom-loading{
  background-color: rgba(255,255,255,.8) !important;
  border-radius: 0.32rem 0.32rem 0 0;
  height: 80% !important;
  bottom: 0 !important;
  top: auto !important;
}
// 国际化的英文需要实现单词的拆分，不然换行时，单词会被分割
.van-toast{
  word-break: normal;   // toast默认是word-break: break-all;
}
</style>
